/**
 * Created by zj on 2018/3/20.
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {Form, Input,Row,Col, Button, Card, Upload, Radio,Icon,message} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './CreateNewVersion.less';
import FooterToolbar from '../../components/FooterToolbar';
const FormItem = Form.Item;
const { TextArea } = Input;

@connect(state => ({
  appVersion: state.appVersion,
}))
@Form.create()
export default class CreateNewVersion extends PureComponent {
  state = {
    apkUrl:'',
    isDisabled:false,
    versionName:'',
    versionCode:'',
    versionType:1,
    disabled:true,
    content:'',
    packageName:'',
    isShowUploadButton:true,
    apkFileList:'',
  };

  /**
   * 点击提交
   * */
  handleSubmit = () => {
    var self = this;
    const { dispatch } = self.props;
    const apkUrl = this.state.apkUrl;
    if(!apkUrl && this.state.versionType == 1){
      message.info("请上传apk");
      return ;
    }
    var versionCode = "";
    var versionName = "";
    var content = "";
    self.props.form.validateFieldsAndScroll((err, fieldsValue) => {
      if (!err) {
        versionCode = fieldsValue.versionCode && fieldsValue.versionCode.valueOf();
        versionName = fieldsValue.versionName && fieldsValue.versionName.valueOf();
        content = fieldsValue.content && fieldsValue.content.valueOf();
      }
    });
    let kk = content.split('\n');
    var str = JSON.stringify(kk); //转换成string
    if(this.state.versionType == 1) {
      var params = {
        versionCode:this.state.versionCode,
        versionName:this.state.versionName,
        packageName:this.state.packageName,
        versionType:1,
        content:str,
      }
    } else {
      var params = {
        versionCode:versionCode,
        versionName:versionName,
        versionType:0,
        content:str,
      }
    }
    if(params.versionCode && params.versionName && params.content) {
      dispatch({
        type: 'appVersion/saveNewVersion',  //请求的action
        payload:params,
        callback:(response) =>{
          if(response.errorCode == '1'){
            message.info("添加成功");
            const backDate = response.data;
            this.setState({
              radioStationDate : backDate
            })
          }
        }
      });
      dispatch({
        type: 'appVersion/turnToVersionList'
      });
    } else {
      message.info('请完善信息')
    }
  }

  handleFileListChange = (info) =>{
    let file = info.file;
    if(file.status == "uploading") {
      this.setState({
        isShowUploadButton:false,
      })
    }
    if(file.status == "done"){
      message.success(file.response.msg);
      this.setState({
        isShowUploadButton:false,
        versionName:file.response.data.apkMeta.versionName,
        versionCode:file.response.data.apkMeta.versionCode,
        isDisabled:true,
        apkUrl:file.response.data.filePath,
        packageName:file.name,
      });
    }
    if(file.status == 'removed'){
      this.setState({
        isDisabled:false
      });
    }
  }

  beforeUpload = file => {
    var fileName = file.name;
    var suffix = fileName.substr(fileName.lastIndexOf('.')+1);
    if(suffix.toLowerCase().endsWith("apk")){
      return true;
    }else{
      message.info('请上传apk文件')
      return false;
    }
  }

  handleTypeChange = (e) => {
    if(e.target.value == 1) {
      this.props.form.resetFields();
      this.setState({
        isShowUploadButton:true,
        disabled:true,
        versionType: e.target.value,
        versionName:'',
        versionCode:'',
        packageName:'',
        content:'',
      })
    } else {
      this.props.form.resetFields();
      this.setState({
        versionType: e.target.value,
        disabled:false,
        versionName:'',
        versionCode:'',
        packageName:'',
        content:'',
      });
    }
  }

  getApkSrc = (apkSrc) => {
    this.setState({
      apkFileList:apkSrc
    });
  }

  removeApk() {
    var self = this;
    const { dispatch } = self.props;
    var params = {
      apkUrl:this.state.apkUrl,
    }
    dispatch({
      type: 'appVersion/delectApk',  //请求的action
      payload:params,
      callback:(response) =>{
      }
    });
    this.props.form.resetFields();
    this.setState({
      versionName:'',
      versionCode:'',
      apkFileList:'',
      packageName:'',
      isShowUploadButton:true,
    });
  }


  render() {
    // console.log('渲染')
    const {submitting} = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };
    const submitFormLayout = {
      wrapperCol: {
        xs: {span: 24, offset: 0},
        sm: {span: 10, offset: 7},
      },
    };

    const props = {
      name: 'file',
      action: '/api/web/versionUpload/apkUpload',
      data:{filePath:'test/apk/'},
      accept:'apk/*',
      disabled:this.state.isDisabled,
      onChange: this.handleFileListChange ,
      beforeUpload: this.beforeUpload,
      onRemove:this.removeApk.bind(this),
    };
    const uploadButton = (
      <Button>
        <Icon type="upload" /> 上传apk包
      </Button>
    );
    const isShowUploadButton = this.state.isShowUploadButton
    return (
      <PageHeaderLayout >
        <Card title="" className={styles.card} bordered={false}>
          <Form
            style={{ marginTop: 8}}
          >
            <FormItem
              {...formItemLayout}
              label="版本类型"
            >
              {getFieldDecorator('versionType', {
                initialValue: "1",
              })(
                <Radio.Group onChange={this.handleTypeChange} disabled={false} >
                  <Radio value="1">android</Radio>
                  <Radio value="0">ios</Radio>
                </Radio.Group>
              )}
            </FormItem>

            {this.state.versionType == 1 ?
              <FormItem
                {...formItemLayout}
                label="上传apk包"
              >
                <Upload {...props} disabled={false} maxFileCount = {1}  getImgSrc={(apkSrc)=> this.getApkSrc(apkSrc)}
                >
                  {
                    isShowUploadButton ? uploadButton: null
                  }

                </Upload>
              </FormItem>:null}

            <FormItem
              {...formItemLayout}
              label="版本号"
            >
              {getFieldDecorator('versionCode', {
                initialValue: [this.state.versionCode],
                rules: [{
                  required: true, message: '请输入版本号',
                }],
              })(
                <Input placeholder=""  disabled={this.state.disabled}/>
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="版本名称"
            >
              {getFieldDecorator('versionName', {
                initialValue: [this.state.versionName],
                rules: [{
                  required: true, message: '请输入版本名称',
                }],
              })(
                <Input placeholder=""  disabled={this.state.disabled}  />
              )}
            </FormItem>
            {this.state.versionType == 1 ?
              <FormItem
                {...formItemLayout}
                label="安装包名"
              >
                {getFieldDecorator('packageName', {
                  initialValue: [this.state.packageName],
                  rules: [{
                    required: true, message: '请输入版本名称',
                  }],
                })(
                  <Input placeholder=""  disabled={this.state.disabled}  />
                )}
              </FormItem>
              : null}

            <FormItem
              {...formItemLayout}
              label="更新内容"
            >
              {getFieldDecorator('content', {
                initialValue: [this.state.content],
                rules: [{
                  required: true, message: '请输入更新内容',
                }],
              })(
                <TextArea
                  style={{ minHeight: 32 }}
                  placeholder=""
                  rows={4}
                />
              )}
            </FormItem>
            <FormItem {...submitFormLayout} style={{ marginTop: 50 }}>
              <Row gutter={16} style={{ marginBottom: '10px' }}>
                <Col className="gutter-row" span={9}>
                </Col>
                <Col className="gutter-row" span={3}>
                  <Button type="primary" htmlType="submit" loading={submitting}
                          onClick={() => this.handleSubmit()} disabled={false} >保存</Button>
                </Col>
                <Col className="gutter-row" span={9}>
                </Col>
              </Row>
            </FormItem>
          </Form>
        </Card>
      </PageHeaderLayout>
    );
  }
}
